package com.example.myapplication.utils;

import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;

/**
 * created by hzs 2021/09/23
 * 号码隔断工具，处理EditText隔断
 */
public class SplitHelper implements TextWatcher {
    private BaseSplit mBaseSplit;
    private EditText mEditText;

    private SplitHelper() {
    }

    private void setSplit(BaseSplit split) {
        mBaseSplit = split;
    }

    private void setEditText(EditText editText) {
        mEditText = editText;
        mEditText.addTextChangedListener(this);
    }

    public void setEnable(boolean enable) {
        if (mBaseSplit != null) {
            mBaseSplit.setEnable(enable);
        }
    }

    /**
     * 获得隔断后的号码
     */
    public String getFormatNumber() {
        if (mBaseSplit != null && mEditText != null) {
            return mBaseSplit.getFormatNumber(mEditText.getText().toString());
        }
        return "";
    }

    /**
     * 获取未隔断的号码
     */
    public String getOriginalText() {
        if (null != mEditText) {
            return mEditText.getText().toString();
        }
        return "";
    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        if (mBaseSplit != null) {
            mBaseSplit.handleSpan(charSequence, mEditText.getText());
        }
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {

    }


    public static class SplitBuilder {
        private boolean mEnable = true;
        private BaseSplit mBaseSplit;
        private EditText mEditText;

        public SplitBuilder setEnable(boolean enable) {
            this.mEnable = enable;
            return this;
        }

        public SplitBuilder setSplit(BaseSplit split) {
            this.mBaseSplit = split;
            return this;
        }

        public SplitBuilder setEditText(EditText editText) {
            this.mEditText = editText;
            return this;
        }

        public SplitHelper build() {
            SplitHelper helper = new SplitHelper();
            if (null != mBaseSplit) {
                helper.setSplit(mBaseSplit);
            }
            if (null != mEditText) {
                helper.setEditText(mEditText);
            }
            helper.setEnable(mEnable);
            return helper;
        }
    }
}
